package com.chase.passwordmaster.components.advancedrecyclerview

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

// Director Pattern
open class PackagedRecyclerViewAdapter<T: RecyclerView.ViewHolder>(
    private val recyclerViewAdapter: RecyclerView.Adapter<T>,
    header: View? = null,
    footer: View? = null
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    companion object {
        private const val TYPE_HEADER = 0
        private const val TYPE_FOOTER = 1
        private const val TYPE_NORMAL = 2
    }

    inner class VH(itemView: View) : RecyclerView.ViewHolder(itemView)

    var mHeaderView: View? = null
        set(value) {
            field = value
            notifyItemInserted(0)
        }

    var mFooterView: View? = null
        set(value) {
            field = value
            notifyItemInserted(itemCount - 1)
        }

    init {
        header?.let { mHeaderView = it }
        footer?.let { mFooterView = it }
    }

    override fun getItemViewType(position: Int): Int {
        if (mHeaderView == null && mFooterView == null) {
            return TYPE_NORMAL
        }
        if (mHeaderView != null && position == 0) {
            //第一个item应该加载Header
            return TYPE_HEADER
        }
        if (mFooterView != null && position == itemCount - 1) {
            //最后一个,应该加载Footer
            return TYPE_FOOTER
        }
        return TYPE_NORMAL
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (viewType == TYPE_HEADER) {
            return mHeaderView?.let { VH(it) }
                ?: throw Exception("mHeaderView in MainRVAdapter is null")
        }

        if (viewType == TYPE_FOOTER) {
            return mFooterView?.let { VH(it) }
                ?: throw Exception("mFooterView in MainRVAdapter is null")
        }
        // 返回被包装类的 ViewHolder，以备后面转换
        return recyclerViewAdapter.onCreateViewHolder(parent, viewType)
    }

    override fun getItemCount(): Int {
        return if (mHeaderView == null && mFooterView == null) {
            recyclerViewAdapter.itemCount
        } else if (mHeaderView == null && mFooterView != null) {
            recyclerViewAdapter.itemCount + 1
        } else if (mHeaderView != null && mFooterView == null) {
            recyclerViewAdapter.itemCount + 1
        } else {
            recyclerViewAdapter.itemCount + 2
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when {
            getItemViewType(position) == TYPE_NORMAL -> recyclerViewAdapter.onBindViewHolder(holder as T, position)
            getItemViewType(position) == TYPE_HEADER -> return
            else -> return
        }
    }
}